/**
 * Created by limei on 2018/6/12.
 */
import MYCONF from '../../myconf';
import {initOdBusAnimation, clearOdBusAnimation} from './odBusAnimation';

const colors = [
  '#00F8FF',
  '#00FF00',
  '#FFF800',
  '#FF0000'
];

function getColor(max, min, param) {
  const factor = (param.data.count - min) / (max - min);
  const index = Math.round(colors.length * factor);
  return colors[index];
};

let popup = null;


export default class odLayerHandler {
  constructor(_view) {
    this._view = _view;
    this.map = _view.map;
    this.echartslayer = null;
  }

  /**
   * .addOdBusStopsLayer()绘制公交站点方法：
   * 参数1:odBusStops为传入的数据。
   * 参数2:数组，数组内存入对应需要操作的字段key，方便调用时字段更改的情况。后续有新需求字段自行添加进数组。
   */
  addOdBusStopsLayer (odBusStops, [title, num, rank, coordinates]) {
    const map = this.map;

    let obBusOption = {
      "type": "FeatureCollection",
      "features": []
    }
    let topflag = 0;    // top计数
    let bottomflag = 0;   // bottom计数
    for (let i = 0; i < odBusStops.length; i++) {
      if (odBusStops[i][rank] <= 10 && topflag < 10) {
        obBusOption.features.push({
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": odBusStops[i][coordinates]
          },
          "properties": {
            "type": "top",
            "title": odBusStops[i][title],
            "number": odBusStops[i][num]
          }
        });
        obBusOption.features.push({
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": odBusStops[i][coordinates]
          },
          "properties": {
            "type": "symbol",
            "title": odBusStops[i][rank]
          }
        });
        topflag++;
      } else if(odBusStops[i][rank] > (odBusStops.length - 10) && bottomflag < 10) {
        obBusOption.features.push({
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": odBusStops[i][coordinates]
          },
          "properties": {
            "type": "bottom",
            "title": odBusStops[i][title],
            "number": odBusStops[i][num]
          }
        });
        bottomflag++;
      } else {
        obBusOption.features.push({
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": odBusStops[i][coordinates]
          },
          "properties": {
            "type": "normal",
            "title": odBusStops[i][title],
            "number": odBusStops[i][num]
          }
        });
      }
    }

    if (map.getSource('bus-stops-source')) return;
    map.addSource("bus-stops-source",{
      "type": "geojson",
      "data": obBusOption
    });

    map.addLayer({
      'id': "bottom-stops-circle",
      'type': 'circle',
      'source': "bus-stops-source",
      'paint': {
        'circle-radius': 13,
        'circle-color': '#49a1fe',
        'circle-stroke-width': 16,
        'circle-stroke-color': '#49a1fe',
        'circle-stroke-opacity': 0.25
      },
      'filter': ['all', ['has', 'type'], ['in', 'type', 'bottom']]
    });
    map.addLayer({
      'id': "normal-stops-circle",
      'type': 'circle',
      'source': "bus-stops-source",
      'paint': {
        'circle-radius': 7,
        'circle-color': '#ff4747',
        'circle-stroke-width': 8,
        'circle-stroke-color': '#ff4747',
        'circle-stroke-opacity': 0.25
      },
      'filter': ['all', ['has', 'type'], ['in', 'type', 'normal']]
    });
    map.addLayer({
      'id': "top-stops-circle",
      'type': 'circle',
      'source': "bus-stops-source",
      'paint': {
        'circle-radius': 16,
        'circle-color': '#ff4747',
        'circle-stroke-width': 18,
        'circle-stroke-color': '#ff4747',
        'circle-stroke-opacity': 0.25
      },
      'filter': ['all', ['has', 'type'], ['in', 'type', 'top']]
    });
    map.addLayer({
      'id': "top-stops-symbol",
      'type': 'symbol',
      'source': "bus-stops-source",
      'layout': {
        'text-field': '{title}',
        'text-anchor': 'center',
        'text-size': 22,
        'text-justify': 'center',
        'text-optional': true,
        'text-allow-overlap': false
      },
      'paint': {
        'text-color': '#ffffff'
      },
      'filter': ['all', ['has', 'title'], ['in', 'type', 'symbol']]
    });

    popup = new minemap.Popup({
      closeButton: true,
      closeOnClick: false,
      offset: [-5, -35]
    });

    map.on('mousemove', function (e) {
      let features = map.queryRenderedFeatures(e.point, {layers: ['top-stops-circle', 'normal-stops-circle', 'bottom-stops-circle']});
      map.getCanvas().style.cursor = (features.length) ? 'pointer' : '';
    });
    map.on('click', function (e) {
      let features = map.queryRenderedFeatures(e.point, {layers: ['top-stops-circle', 'normal-stops-circle', 'bottom-stops-circle']});
      if (!features.length) {
        popup.remove();
        return;
      }
      let feature = features[0];
      popup.setLngLat(feature.geometry.coordinates)
        .setHTML("<div class='warn-popup' style='width: 220px;'><p class='p-tip'><span class='title-tip'>" + feature.properties.title + "</span></p>" +
          "<p class='p-tip'><span class='name-tip'>客流量：</span><span>" + feature.properties.number + "</span></p>" + 
          "<span class='content-tip-large'></span></div>")
        .addTo(map);
    });

    initOdBusAnimation(map);
  }

  /**
   * .addOdBusLinesLayer()绘制公交站点方法：
   * 参数1:odBusLines为传入的数据。
   * 参数2:数组，数组内存入对应需要操作的字段key，方便调用时字段更改的情况。后续有新需求字段自行添加进数组。
   */
  addOdBusLinesLayer (odBusLines, [coordinates]) {
    const map = this.map;
    
    let lines = [];
    odBusLines.forEach(line => {
      lines.push(line[coordinates]);
    });

    if (map.getSource('bus-lines-source')) return;
    map.addSource("bus-lines-source",{
      "type": "geojson",
      "data": {
        "type": "FeatureCollection",
        "features": [
          {
            "type": "Feature",
            "geometry": {
              "type": "MultiLineString",
              "coordinates": lines
            }
          }
        ]
      }
    });

    map.addLayer({
      'id': 'bus-lines-line',
      'type': 'line',
      'source': "bus-lines-source",
      'layout': {
        'line-cap': 'round',
        'line-join': 'round'
      },
      'paint': {
        'line-color': '#ff4747',
        'line-width': 2
      }
    });
  }

  destroyOdBusLayer () {
    const map = this.map;
    let layerids = ['top-stops-circle', 'normal-stops-circle', 'bottom-stops-circle', 'top-stops-symbol', 'bus-lines-line'];

    if (map.getSource('bus-stops-source')) map.removeSource('bus-stops-source');
    if (map.getSource('bus-lines-source')) map.removeSource('bus-lines-source');

    layerids.forEach(id => {
      if (map.getLayer(id)) map.removeLayer(id);
    });

    popup.remove();
    clearOdBusAnimation();
  }
  
  addOdLayer(lineData, scatterData, max, min, center, zoom) {
    const series = [{
      name: 'bgLine',
      type: 'lines',
      coordinateSystem: 'GLMap',
      zlevel: 1,
      // symbol: ['none', 'arrow'],
      // symbolSize: 10,
      lineStyle: {
        normal: {
          color: getColor.bind(null, max, min),
          width: 2,
          opacity: 0.5,
          curveness: 0.2
        }
      },
      data: lineData
    }, {
      name: 'scatter',
      type: 'effectScatter',
      coordinateSystem: 'GLMap',
      zlevel: 2,
      rippleEffect: {
        scale: 50,
        brushType: 'stroke'
      },
      label: {
        normal: {
          show: true,
          position: 'right',
          formatter: '{b}'
        }
      },
      symbolSize: 1,
      itemStyle: {
        normal: {
          show: true,
          color: getColor.bind(null, max, min)
        }
      },
      data: scatterData
    }, {
      name: 'sLine',
      type: 'lines',
      coordinateSystem: 'GLMap',
      zlevel: 3,
      effect: {
        show: true,
        period: 6,
        trailLength: 0.4,
        symbolSize: 5
      },
      lineStyle: {
        normal: {
          color: getColor.bind(null, max, min),
          width: 0,
          curveness: 0.2
        }
      },
      data: lineData
    }, {
      name: 'lLine',
      type: 'lines',
      coordinateSystem: 'GLMap',
      zlevel: 4,
      effect: {
        show: true,
        period: 6,
        trailLength: 0.4,
        opacity: 0.1,
        symbolSize: 20
      },
      lineStyle: {
        normal: {
          color: getColor.bind(null, max, min),
          width: 0,
          curveness: 0.2
        }
      },
      data: lineData
    }];

    //组装option
    const option = {
      GLMap: {
        roam: true
      },
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(0,0,0,0)',
        formatter: function (param) {
          return param.data.name + '->' + param.data.dest + ': ' + param.data.count;
        }
      },
      series: series
    };

    /**
     * 最重要的就是下面这两句，首先创建一个echartslayer
     * 然后再调用echartslayer.chart.setOption 这个charts就是echarts.init 返回的实例
     * echartslayer 拥有的方法
     * resize 重置大小
     * remove 删除
     * dispose 清空
     * getChartId 获取div对应id号，方便样式设置
     */
    if (!this.echartslayer) {
      this.echartslayer = minemap.Template.create({
        map: this._view.map,
        type: 'od'
      });
    }
    this.echartslayer.chart.setOption(option);

    this.map.easeTo({
      center,
      zoom
    })
  }

  distoryOdLayer() {
    if (this.echartslayer) {
      this.echartslayer.remove();
      this.echartslayer = null;
    }
  }
}
